<template>
	<view class="register-container">
		<!-- 顶部装饰波浪 -->
		<view class="wave-box">
			<image class="wave" src="/static/images/wave-1.png" mode="scaleToFill"></image>
		</view>
		
		<!-- 返回按钮 -->
		<!-- <view class="back-btn" @click="goBack">
			<uni-icons type="back" size="30" color="#FFFFFF" style="margin-right: 10rpx;"></uni-icons>
		</view> -->
		
		<!-- 标题 -->
		<view class="header">
			<text class="title">注册账号</text>
			<text class="subtitle">创建您的个人记账本账号</text>
		</view>
		
		<!-- 注册表单 -->
		<view class="form-container">
			<!-- 用户名 -->
			<view class="input-group" :class="{ 'error': errors.username }">
				<uni-icons type="person" size="25" :color="textColor" style="margin-right: 10rpx;"></uni-icons>
				<input 
					class="input" 
					type="text" 
					v-model="registerForm.username" 
					placeholder="请输入用户名" 
					placeholder-class="placeholder"
					@blur="validateUsername"
				/>
			</view>
			<text v-if="errors.username" class="error-message">{{ errors.username }}</text>
			
			<!-- 密码 -->
			<view class="input-group" :class="{ 'error': errors.password }">
				<uni-icons type="locked" size="25" :color="textColor" style="margin-right: 10rpx;"></uni-icons>
				<input 
					class="input" 
					:type="showPassword ? 'text' : 'password'" 
					v-model="registerForm.password" 
					placeholder="请输入密码" 
					placeholder-class="placeholder"
					@blur="validatePassword"
				/>
				<uni-icons :type="showPassword ? 'eye' : 'eye-slash'" size="25" :color="textColor" @click="togglePasswordVisibility"></uni-icons>
			</view>
			<text v-if="errors.password" class="error-message">{{ errors.password }}</text>
			
			<!-- 确认密码 -->
			<view class="input-group" :class="{ 'error': errors.confirmPassword }">
				<uni-icons type="locked" size="25" :color="textColor" style="margin-right: 10rpx;"></uni-icons>
				<input 
					class="input" 
					:type="showConfirmPassword ? 'text' : 'password'" 
					v-model="registerForm.confirmPassword" 
					placeholder="请确认密码" 
					placeholder-class="placeholder"
					@blur="validateConfirmPassword"
				/>
				<uni-icons :type="showConfirmPassword ? 'eye' : 'eye-slash'" size="25" :color="textColor" @click="toggleConfirmPasswordVisibility"></uni-icons>
			</view>
			<text v-if="errors.confirmPassword" class="error-message">{{ errors.confirmPassword }}</text>
			
			<!-- 邮箱 -->
			<view class="input-group" :class="{ 'error': errors.email }">
				<uni-icons type="email" size="25" :color="textColor" style="margin-right: 10rpx;"></uni-icons>
				<input 
					class="input" 
					type="text" 
					v-model="registerForm.email" 
					placeholder="请输入邮箱" 
					placeholder-class="placeholder"
					@blur="validateEmail"
				/>
			</view>
			<text v-if="errors.email" class="error-message">{{ errors.email }}</text>
			
			<!-- 验证码 -->
			<view class="input-group code-group" :class="{ 'error': errors.code }">
				<uni-icons type="shield" size="25" :color="textColor" style="margin-right: 10rpx;"></uni-icons>
				<input 
					class="input" 
					type="text" 
					v-model="registerForm.code" 
					placeholder="请输入验证码" 
					placeholder-class="placeholder"
					@blur="validateCode"
				/>
				<button 
					class="code-btn" 
					:disabled="codeBtnDisabled || isLoading" 
					@click="sendVerificationCode"
				>
					{{ codeBtnText }}
				</button>
			</view>
			<text v-if="errors.code" class="error-message">{{ errors.code }}</text>
			
			<!-- 注册按钮 -->
			<button class="register-btn" @click="handleRegister" :disabled="isLoading">
				<text v-if="!isLoading">注 册</text>
				<view v-else class="loading-circle"></view>
			</button>
			
			<!-- 登录链接 -->
			<view class="login-link">
				<text>已有账号？</text>
				<text class="link" @click="goToLogin">立即登录</text>
			</view>
		</view>
	</view>
</template>

<script>
import { register, sendEmailCode } from '@/api/apis.js';
import { themeMixin } from '@/utils/theme.js';

export default {
	mixins: [themeMixin], // 混入主题工具
	data() {
		return {
			registerForm: {
				username: '',
				password: '',
				confirmPassword: '',
				email: '',
				code: ''
			},
			errors: {
				username: '',
				password: '',
				confirmPassword: '',
				email: '',
				code: ''
			},
			showPassword: false,
			showConfirmPassword: false,
			isLoading: false,
			codeBtnDisabled: false,
			codeBtnText: '获取验证码',
			countdown: 60,
			countdownTimer: null
		}
	},
	watch: {
		'registerForm.email': function(newVal, oldVal) {
			if (newVal !== oldVal && this.registerForm.code) {
				// 清空验证码
				this.registerForm.code = '';
				// 提示用户
				uni.showToast({
					title: '邮箱已修改，请重新获取验证码',
					icon: 'none'
				});
				
				// 如果邮箱变更，并且不是当前正在倒计时的邮箱，则重置按钮状态
				const cachedEmail = uni.getStorageSync('verification_email');
				if (cachedEmail !== newVal) {
					// 清除之前的倒计时
					if (this.countdownTimer) {
						clearInterval(this.countdownTimer);
					}
					this.codeBtnDisabled = false;
					this.codeBtnText = '获取验证码';
				}
			}
		}
	},
	onLoad() {
		// 页面加载时检查是否有未完成的倒计时
		this.checkCachedCountdown();
	},
	onUnload() {
		// 页面卸载时清除定时器
		if (this.countdownTimer) {
			clearInterval(this.countdownTimer);
		}
	},
	methods: {
		// 检查缓存中的倒计时
		checkCachedCountdown() {
			const endTime = uni.getStorageSync('verification_end_time');
			const email = uni.getStorageSync('verification_email');
			
			if (endTime && email) {
				const now = new Date().getTime();
				const remainingTime = Math.floor((endTime - now) / 1000);
				
				// 如果倒计时未结束
				if (remainingTime > 0) {
					// 设置当前邮箱为缓存中的邮箱
					this.registerForm.email = email;
					// 重新开始倒计时
					this.codeBtnDisabled = true;
					this.resumeCountdown(remainingTime);
				} else {
					// 倒计时已结束，清除缓存
					this.clearCountdownCache();
				}
			}
		},
		
		// 清除倒计时缓存
		clearCountdownCache() {
			uni.removeStorageSync('verification_end_time');
			uni.removeStorageSync('verification_email');
		},
		
		// 切换密码可见性
		togglePasswordVisibility() {
			this.showPassword = !this.showPassword;
		},
		
		// 切换确认密码可见性
		toggleConfirmPasswordVisibility() {
			this.showConfirmPassword = !this.showConfirmPassword;
		},
		
		// 验证用户名
		validateUsername() {
			if (!this.registerForm.username) {
				this.errors.username = '请输入用户名';
				return false;
			}
			
			if (this.registerForm.username.length < 3) {
				this.errors.username = '用户名长度不能少于3个字符';
				return false;
			}
			
			if (this.registerForm.username.length > 20) {
				this.errors.username = '用户名长度不能超过20个字符';
				return false;
			}
			
			// 只允许字母、数字和下划线
			const usernameRegex = /^[a-zA-Z0-9_]+$/;
			if (!usernameRegex.test(this.registerForm.username)) {
				this.errors.username = '用户名只能包含字母、数字和下划线';
				return false;
			}
			
			this.errors.username = '';
			return true;
		},
		
		// 验证密码
		validatePassword() {
			if (!this.registerForm.password) {
				this.errors.password = '请输入密码';
				return false;
			}
			
			if (this.registerForm.password.length < 6) {
				this.errors.password = '密码长度不能少于6个字符';
				return false;
			}
			
			if (this.registerForm.password.length > 20) {
				this.errors.password = '密码长度不能超过20个字符';
				return false;
			}
			
			// 密码强度验证：至少包含一个字母和一个数字
			const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d).+$/;
			if (!passwordRegex.test(this.registerForm.password)) {
				this.errors.password = '密码必须包含至少一个字母和一个数字';
				return false;
			}
			
			this.errors.password = '';
			return true;
		},
		
		// 验证确认密码
		validateConfirmPassword() {
			if (!this.registerForm.confirmPassword) {
				this.errors.confirmPassword = '请确认密码';
				return false;
			}
			
			if (this.registerForm.confirmPassword !== this.registerForm.password) {
				this.errors.confirmPassword = '两次输入的密码不一致';
				return false;
			}
			
			this.errors.confirmPassword = '';
			return true;
		},
		
		// 验证邮箱
		validateEmail() {
			if (!this.registerForm.email) {
				this.errors.email = '请输入邮箱';
				return false;
			}
			
			// 邮箱格式验证
			const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
			if (!emailRegex.test(this.registerForm.email)) {
				this.errors.email = '请输入有效的邮箱地址';
				return false;
			}
			
			this.errors.email = '';
			return true;
		},
		
		// 验证验证码
		validateCode() {
			if (!this.registerForm.code) {
				this.errors.code = '请输入验证码';
				return false;
			}
			
			if (this.registerForm.code.length !== 6) {
				this.errors.code = '验证码长度应为6位';
				return false;
			}
			
			// 验证码只能是数字
			const codeRegex = /^\d+$/;
			if (!codeRegex.test(this.registerForm.code)) {
				this.errors.code = '验证码只能包含数字';
				return false;
			}
			
			this.errors.code = '';
			return true;
		},
		
		// 验证所有表单
		validateForm() {
			const isUsernameValid = this.validateUsername();
			const isPasswordValid = this.validatePassword();
			const isConfirmPasswordValid = this.validateConfirmPassword();
			const isEmailValid = this.validateEmail();
			const isCodeValid = this.validateCode();
			
			return isUsernameValid && isPasswordValid && isConfirmPasswordValid && isEmailValid && isCodeValid;
		},
		
		// 发送验证码
		async sendVerificationCode() {
			// 验证邮箱
			if (!this.validateEmail()) {
				return;
			}
			
			this.codeBtnDisabled = true;
			
			try {
				await sendEmailCode({
					email: this.registerForm.email,
					type: 'register' // 假设后端需要一个类型参数来区分不同场景的验证码
				});
				
				uni.showToast({
					title: '验证码已发送',
					icon: 'success'
				});
				
				// 开始倒计时
				this.startCountdown();
				
				// 保存邮箱到缓存，用于标识当前正在倒计时的邮箱
				uni.setStorageSync('verification_email', this.registerForm.email);
			} catch (error) {
				console.error('发送验证码失败:', error);
				this.codeBtnDisabled = false;
			}
		},
		
		// 开始倒计时
		startCountdown() {
			// 清除可能存在的定时器
			if (this.countdownTimer) {
				clearInterval(this.countdownTimer);
			}
			
			// 设置结束时间并存储到缓存
			const endTime = new Date().getTime() + this.countdown * 1000;
			uni.setStorageSync('verification_end_time', endTime);
			
			this.countdown = 60;
			this.codeBtnText = `${this.countdown}秒后重发`;
			
			this.countdownTimer = setInterval(() => {
				this.countdown--;
				this.codeBtnText = `${this.countdown}秒后重发`;
				
				if (this.countdown <= 0) {
					clearInterval(this.countdownTimer);
					this.countdownTimer = null;
					this.codeBtnDisabled = false;
					this.codeBtnText = '获取验证码';
					// 清除缓存
					this.clearCountdownCache();
				}
			}, 1000);
		},
		
		// 恢复倒计时（从缓存中恢复）
		resumeCountdown(remainingSeconds) {
			this.countdown = remainingSeconds;
			this.codeBtnText = `${this.countdown}秒后重发`;
			
			this.countdownTimer = setInterval(() => {
				this.countdown--;
				this.codeBtnText = `${this.countdown}秒后重发`;
				
				if (this.countdown <= 0) {
					clearInterval(this.countdownTimer);
					this.countdownTimer = null;
					this.codeBtnDisabled = false;
					this.codeBtnText = '获取验证码';
					// 清除缓存
					this.clearCountdownCache();
				}
			}, 1000);
		},
		
		// 注册处理
		async handleRegister() {
			// 表单验证
			if (!this.validateForm()) {
				return;
			}
			
			this.isLoading = true;
			
			try {
				const res = await register({
					username: this.registerForm.username,
					password: this.registerForm.password,
					email: this.registerForm.email,
					code: this.registerForm.code
				});
				
				// 注册成功
				uni.showToast({
					title: '注册成功',
					icon: 'success'
				});
				
				// 清除验证码相关缓存
				this.clearCountdownCache();
				
				// 延迟跳转到登录页
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}, 1500);
			} catch (error) {
				console.error('注册失败:', error);
			} finally {
				this.isLoading = false;
			}
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack();
		},
		
		// 去登录
		goToLogin() {
			uni.navigateTo({
				url: '/pages/login/login'
			});
		}
	}
}
</script>

<style lang="scss">
.register-container {
    box-sizing: border-box;
	min-height: 100vh;
	display: flex;
	flex-direction: column;
	background-color: $background-color;
	position: relative;
	padding-bottom: 40rpx;
	
	// 波浪装饰
	.wave-box {
		width: 100%;
		height: 480rpx;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 1;
		overflow: hidden;
		background-color: $primary-color;
		
		.wave {
			width: 100%;
			height: 230rpx;
			position: absolute;
			bottom: 0;
			left: 0;
			background-color: $primary-color;
		}
	}
	
	// 返回按钮
	.back-btn {
		position: absolute;
		top: 80rpx;
		left: 30rpx;
		width: 80rpx;
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 10;
		
		.iconfont {
			font-size: 50rpx;
			color: #fff;
		}
	}
	
	// 头部标题
	.header {
		margin-top: 100rpx;
		// padding: 60rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
		z-index: 2;
		
		.title {
			font-size: $font-size-xlarge;
			font-weight: bold;
			color: $text-color-white;
			margin-bottom: $spacing-small;
			text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
		}
		
		.subtitle {
			font-size: $font-size-base;
			color: rgba(255, 255, 255, 0.9);
		}
	}
	
	// 表单容器
	.form-container {
		flex: 1;
		padding: $spacing-large;
		margin-top: 50rpx;
		z-index: 2;
		
		.input-group {
			@include input-style;
			
			&.error {
				border: 1px solid $error-color;
			}
			
			&.code-group {
				padding-right: 0;
			}
			
			.iconfont {
				font-size: 40rpx;
				color: $primary-color;
				margin-right: $spacing-small;
			}
			
			.input {
				flex: 1;
				height: 100%;
				font-size: $font-size-medium;
			}
			
			.placeholder {
				color: $text-color-lighter;
			}
			
			.code-btn {
				height: 100%;
				padding: 0 30rpx;
				background-color: $primary-color;
				color: #fff;
				font-size: $font-size-small;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 0 $border-radius-large $border-radius-large 0;
				white-space: nowrap;
				
				&:disabled {
					background-color: #cccccc;
				}
			}
		}
		
		.error-message {
			color: $error-color;
			font-size: $font-size-small;
			margin: -20rpx 0 20rpx 20rpx;
		}
		
		.register-btn {
			@include button-primary;
			margin-top: $spacing-xlarge;
			
			.loading-circle {
				width: 40rpx;
				height: 40rpx;
				border: 4rpx solid rgba(255, 255, 255, 0.3);
				border-top-color: $text-color-white;
				border-radius: 50%;
				animation: spin 1s linear infinite;
			}
		}
		
		.login-link {
			margin-top: $spacing-large;
			text-align: center;
			font-size: $font-size-base;
			color: $text-color-light;
			
			.link {
				color: $primary-color;
				margin-left: 10rpx;
			}
		}
	}
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

// 图标字体
@font-face {
	font-family: "iconfont";
	src: url('data:font/woff2;charset=utf-8;base64,d09GMgABAAAAAAOYAAsAAAAAB8AAAANLAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHFQGYACDHAqDIIJ5ATYCJAMQCwoABCAFhGcHShtpBhHVm5HIvkgwbhrDRRQqFFcPvpj5a+Jh/v3+7XPuvW9m/n+qSTrpdpJokkknk0QSjVRI0EiQJoVE6IQO7+f5bl9QJAuUBXQBlZlJg6ICZWjZCbMTdv7/OWa8NA6sf5fNJaOgowEcJdCAoqJFJOAdyA38D2MXF3GYgGbJBpGjcwvroGCQzwkQV0cGQSGxUgMZqA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4QjQAAAAA=') format('woff2');
}

.iconfont {
	font-family: "iconfont" !important;
	font-size: 16px;
	font-style: normal;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}

.icon-user:before {
	content: "\e7ae";
}

.icon-lock:before {
	content: "\e7c9";
}

.icon-eye:before {
	content: "\e78f";
}

.icon-eye-close:before {
	content: "\e8ff";
}

.icon-email:before {
	content: "\e74f";
}

.icon-shield:before {
	content: "\e7cf";
}

.icon-back:before {
	content: "\e7ed";
}
</style> 